import axios from 'axios'
import { getToken, removeUserInfo } from '@/utils/index'
import { ElMessage } from 'element-plus'
import router from '@/router'

const request = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL
})

request.interceptors.request.use(function (config) {
  // 获取token 添加到请求头，做接口token校验
  if (getToken()) {
    config.headers.token = getToken()
  }
  return config
}, function (error) {
  return Promise.reject(error)
})
request.interceptors.response.use(function (res) {
  switch (res.data.code) {
    case 401:
      removeUserInfo()
      ElMessage({
        type: 'error',
        message: '登录过期，请重新登录',
        onClose: () => {
          router.replace('/login')
        }
      })
      break
    case 403:
      ElMessage({
        type: 'error',
        message: '未登录',
        onClose: () => {
          router.replace('/login')
        }
      })
      break
    default:
      break
  }
  return res
}, function (error) {
  return Promise.reject(error)
})

export default request
